﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Win32;
using System.IO;

namespace ktds_test_module
{
    public partial class test_main : Form
    {
        public test_main()
        {
            InitializeComponent();
        }

        private void test_main_Load(object sender, EventArgs e)
        {
        }

        private String Excute_TaskList()
        {
            ProcessStartInfo cmdProcess = new ProcessStartInfo();
            cmdProcess.WindowStyle = ProcessWindowStyle.Hidden;
            cmdProcess.CreateNoWindow = true;
            cmdProcess.FileName = @"cmd";
            cmdProcess.UseShellExecute = false;
            cmdProcess.RedirectStandardOutput = true;
            cmdProcess.RedirectStandardInput = true;
            cmdProcess.RedirectStandardError = true;

            //Product ID
            //cmdProcess.Arguments += "{731962DB-76B1-XXE8-XXA7-3XX57C9F6EXX}";

            Process pro = new Process();
            pro.StartInfo = cmdProcess;
            pro.Start();
            pro.StandardInput.Write(@"tasklist /svc /nh " + Environment.NewLine);
            pro.StandardInput.Close();

            string result = pro.StandardOutput.ReadToEnd();
            StringBuilder sb = new StringBuilder();
            sb.Append(result);

            pro.WaitForExit();
            pro.Close();

            return sb.ToString();
        }

        private void CheckTheReg(RegistryKey regpara)
        {
            // 만약 AutoRestart 값이 없으면
            if (regpara.GetValue("AutoRestart") == null)
            {
                // 노 체크
                txb_print_result.Text += "key 없음" + Environment.NewLine;
            }
            else  // 값이 있으면
            {
                // 체크
                txb_print_result.Text += "key 있음" + Environment.NewLine;
            }
        }

        // 오토스타트 등록
        public void AutoStartReg(RegistryKey regpara)
        {
            if (regpara == null)
            {
                regpara = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            }

            regpara.SetValue("AutoRestart", Application.ExecutablePath.ToString());
            txb_print_result.Text += "자동 실행 등록 완료" + Environment.NewLine;
        }

        // 오토스타트 삭제
        public void AutoStartDel(RegistryKey regpara)
        {
            if (regpara == null)
            {
                regpara = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            }
            regpara = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            regpara.DeleteValue("AutoRestart", false);
            txb_print_result.Text += "자동 실행 삭제 완료" + Environment.NewLine;
        }

        private void bt_delete_reg_Click(object sender, EventArgs e)
        {
            txb_print_result.Clear();
            RegistryKey regkey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            txb_print_result.Text += "Key 위치 SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run" + Environment.NewLine;
            CheckTheReg(regkey);
            AutoStartDel(regkey);
            CheckTheReg(regkey);
        }

        private void bt_insert_reg_Click(object sender, EventArgs e)
        {
            txb_print_result.Clear();
            // Registry 에서 Sub Key를 가져온다
            RegistryKey regkey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            txb_print_result.Text += "Key 위치 : SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run" + Environment.NewLine;
            CheckTheReg(regkey);
            AutoStartReg(regkey);
            CheckTheReg(regkey);
        }

        private void bt_print_tasklist_Click(object sender, EventArgs e)
        {
            txb_print_result.Clear();
            txb_print_result.Text = Excute_TaskList();
        }

        private void bt_checkprocess_Click(object sender, EventArgs e)
        {
            txb_print_result.Clear();
            string result = Check_process();
            if (result == "정보: 실행 중인 작업 중 지정된 조건에 일치하는 작업이 없습니다.")
            {
                txb_print_result.Text += "프로그램 실행 안됨" + Environment.NewLine;
            }
            else
            {
                txb_print_result.Text += "프로그램 실행 됨" + Environment.NewLine;
            }

        }

        private String Check_process()
        {
            ProcessStartInfo cmdProcess = new ProcessStartInfo();
            cmdProcess.WindowStyle = ProcessWindowStyle.Hidden;
            cmdProcess.CreateNoWindow = true;
            cmdProcess.FileName = @"cmd";
            cmdProcess.UseShellExecute = false;
            cmdProcess.RedirectStandardOutput = true;
            cmdProcess.RedirectStandardInput = true;
            cmdProcess.RedirectStandardError = true;

            //Product ID
            //cmdProcess.Arguments += "{731962DB-76B1-XXE8-XXA7-3XX57C9F6EXX}";

            string pro_name = "a.exe";
            txb_print_result.Text += pro_name + " 프로그램 실행 여부 체크" + Environment.NewLine;
            Process pro = new Process();
            pro.StartInfo = cmdProcess;
            pro.Start();
            pro.StandardInput.Write(@"tasklist /FI ""imagename eq " + pro_name + @" "" /NH " + Environment.NewLine);
            pro.StandardInput.Close();

            string result = pro.StandardOutput.ReadToEnd();
            StringBuilder sb = new StringBuilder();
            sb.Append(result);

            pro.WaitForExit();
            pro.Close();

            txb_print_result.Text += sb.ToString() + Environment.NewLine;
            return sb.ToString();
        }

        private void bt_conDB_Click(object sender, EventArgs e)
        {
            C_DBConnect dbcon = new C_DBConnect();
            dbcon.Connect_DB();
        }

        private void bt_sung_Click(object sender, EventArgs e)
        {
            txb_print_result.Clear();
            CheckTheProgramWithSung();
        }

        private void CheckTheProgramWithSung()
        {
            RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", true);

            String[] InstalledProgramList = regkey.GetSubKeyNames();
            txb_print_result.Text += "count : " + InstalledProgramList.Count() + Environment.NewLine;

            string check_program = "DLP V3.0 Core Client";

            for (int i = 0; i < InstalledProgramList.Count(); i++)
            {
                if (InstalledProgramList[i].Equals(check_program))
                {
                    txb_print_result.Text += "DLP V3.0 Core Client가 설치 되어 있습니다." + Environment.NewLine;
                    break;
                }
            }
        }

        private void bt_parsing_text_Click(object sender, EventArgs e)
        {
            String InputText = txb_pring_result2.Text;
            txb_pring_result2.Text += Environment.NewLine + "=========================================" + Environment.NewLine;
            txb_pring_result2.Text += InputText;
            txb_pring_result2.Clear();
            txb_pring_result2.Text += "결과 출력 ========================" + Environment.NewLine;
            ParsingTracerouteText(InputText);
        }

        private void ParsingTracerouteText(String ParaString)
        {
            String[] FirstSplitText = ParaString.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            //String[] SecondSplitText = new String[100];
            String[] IpInfo = new String[100];

            for (int i = 0; i < FirstSplitText.Length; i++)
            {
                String[] SecondSplitText = FirstSplitText[i].Split(' ');

                for (int y = 0; y < SecondSplitText.Length; y++)
                {
                    IpInfo[i] = SecondSplitText[y];

                    if (IpInfo[i].Contains('[') || IpInfo[i].Contains(']'))
                    {
                        IpInfo[i] = IpInfo[i].Replace('[', ' ').Trim();
                        IpInfo[i] = IpInfo[i].Replace(']', ' ').Trim();
                    }
                }
                txb_pring_result2.Text += IpInfo[i].ToString() + Environment.NewLine;
            }
        }

        private void bt_openfile_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = @"C:\";
            openFileDialog1.ShowDialog();

            if (openFileDialog1.FileName.Length > 0)
            {
                txb_pring_result2.Text = openFileDialog1.FileName;
            }

            txb_pring_result2.Clear();
            txb_pring_result2.Text += "결과 출력 ========================" + Environment.NewLine;

            ReadFile(openFileDialog1.FileName.ToString());
        }

        private void ReadFile(String FileName)
        {
            StreamReader sr = new StreamReader(FileName, Encoding.GetEncoding("euc-kr"));
            String ReadedTraceroute = null;

            while (!sr.EndOfStream)
            {
                ReadedTraceroute += sr.ReadLine() + Environment.NewLine;
            }

            sr.Close();

            ParsingTracerouteText(ReadedTraceroute);
        }

        private void bt_ExcuteTraceroute_Click(object sender, EventArgs e)
        {
            test_PrintTwoTraceResult();
        }

        private void test_PrintTwoTraceResult()
        {
            txb_pring_result2.Clear();

            String InsertSrcIPInfo = null;
            String InsertDstIPInfo = null;

            if (txb_InsertSrcIP.Text == "" && txb_InsertDstIP.Text == "")
            {
                MessageBox.Show("Src IP와 Dst IP 정보를 입력해 주세요");
            }
            else
            {
                InsertSrcIPInfo = txb_InsertSrcIP.Text.Trim();
                InsertDstIPInfo = txb_InsertDstIP.Text.Trim();

                List<InfoTraceroute> Resert_Src_Traceroute = new List<InfoTraceroute>();
                List<InfoTraceroute> Resert_Dst_Traceroute = new List<InfoTraceroute>();

                List<string> Src_IP_Info = new List<string>();
                List<string> Dst_IP_Info = new List<string>();

                C_Traceroute Src_traceroute = new C_Traceroute();
                C_Traceroute Dst_traceroute = new C_Traceroute();

                Resert_Src_Traceroute = Src_traceroute.ExcuteTraceroute(InsertSrcIPInfo);

                txb_pring_result2.Text += "Src Trace Result" + Environment.NewLine;
                for (int i = 0; i < Resert_Src_Traceroute.Count(); i++)
                {
                    txb_pring_result2.Text += Resert_Src_Traceroute[i].EndPoint.ToString() + Environment.NewLine;
                    Src_IP_Info.Add(Resert_Src_Traceroute[i].EndPoint.ToString());
                }

                Resert_Dst_Traceroute = Dst_traceroute.ExcuteTraceroute(InsertDstIPInfo);

                txb_pring_result2.Text += Environment.NewLine;
                txb_pring_result2.Text += "=====================================" + Environment.NewLine;
                txb_pring_result2.Text += Environment.NewLine;
                txb_pring_result2.Text += "Dst Trace Result" + Environment.NewLine;
                for (int i = 0; i < Resert_Dst_Traceroute.Count(); i++)
                {
                    if (Resert_Dst_Traceroute[i].EndPoint.ToString() == null)
                    {
                        txb_pring_result2.Text += "*" + Environment.NewLine;
                    }
                    else
                    {
                        txb_pring_result2.Text += Resert_Dst_Traceroute[i].EndPoint.ToString() + Environment.NewLine;
                    }
                    Dst_IP_Info.Add(Resert_Dst_Traceroute[i].EndPoint.ToString());
                }
            }
        }

        private void btn_CompareTest_Click(object sender, EventArgs e)
        {
            CombineTwoTrace();
        }

        private void CombineTwoTrace()
        {
            txb_pring_result2.Clear();

            String InsertSrcIPInfo = null;
            String InsertDstIPInfo = null;

            C_DBConnect dbcon = new C_DBConnect();

            if (txb_InsertSrcIP.Text == "" && txb_InsertDstIP.Text == "")
            {
                MessageBox.Show("Src IP와 Dst IP 정보를 입력해 주세요");
            }
            else
            {
                InsertSrcIPInfo = txb_InsertSrcIP.Text.Trim();
                InsertDstIPInfo = txb_InsertDstIP.Text.Trim();

                List<InfoTraceroute> Resert_Src_Traceroute = new List<InfoTraceroute>();
                List<InfoTraceroute> Resert_Dst_Traceroute = new List<InfoTraceroute>();

                List<string> Src_IP_Info = new List<string>();
                List<string> Dst_IP_Info = new List<string>();

                C_Traceroute Src_traceroute = new C_Traceroute();
                C_Traceroute Dst_traceroute = new C_Traceroute();

                Resert_Src_Traceroute = Src_traceroute.ExcuteTraceroute(InsertSrcIPInfo);
                Resert_Dst_Traceroute = Dst_traceroute.ExcuteTraceroute(InsertDstIPInfo);

                int Index_Src_Traceroute = 0;
                int Index_Dst_Traceroute = 0;
                
                String Src_Group_code = null;
                String Dst_Group_code = null;

                // 공통 부분 추출
                for (int i = 0; i < Resert_Src_Traceroute.Count; i++)
                {
                    for (int y = 0; y < Resert_Dst_Traceroute.Count; y++)
                    {
                        // DB의 데이터를 가지고 비교
                        // IP정보를 가지고 DB의 그룹 코드 추출
                        // 그룹 코드 비교(두개의 IP가 동일한가?)
                        Src_Group_code = dbcon.SelectGroupKey(Resert_Src_Traceroute[i].ToString());
                        Dst_Group_code = dbcon.SelectGroupKey(Resert_Dst_Traceroute[y].ToString());

                        if (Src_Group_code == Dst_Group_code)
                        {
                            Index_Src_Traceroute = Src_IP_Info.IndexOf(Resert_Src_Traceroute[i].ToString());
                            Index_Dst_Traceroute = Dst_IP_Info.IndexOf(Resert_Dst_Traceroute[y].ToString());
                        }
                    }
                }

                if (Src_Group_code == null || Dst_Group_code == null)
                {
                }

                // 결합 로직
                List<string> Result_IP_Info = new List<string>();

                for (int i = Index_Src_Traceroute; i > 0; i--)
                {
                    Result_IP_Info.Add(Src_IP_Info[i]);
                    txb_pring_result2.Text += Src_IP_Info[i].ToString();
                }

                for (int i = Index_Dst_Traceroute; i < Dst_IP_Info.Count(); i++)
                {
                    Result_IP_Info.Add(Dst_IP_Info[i]);
                    txb_pring_result2.Text += Dst_IP_Info[i].ToString();
                }                
            }
        }
    }
}
